import React, { useEffect, useState } from 'react'
import { Form, Card, Input, Select, Button, Space, Table } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import {
  reqGetHospitalList,
  reqGetProvince,
  reqGetCityOrDistrict,
} from '@api/hospital/hospitalList'
import {
  IhospitalList,
  IhospitalItem,
  IresList,
} from '@api/hospital/hospitalList/model/hospitalListTypes'
import { useNavigate } from 'react-router-dom'

// 注意: Option是从Select组件中解构的
const { Option } = Select

let flag = false //是否点击查询的标记: true则点击了,false则没点击

export default function HospitalList() {
  const navigate = useNavigate()
  const [form] = Form.useForm()
  // 医院列表数据
  const [hospitalList, setHospitalList] = useState<IhospitalList>([])
  //分页相关的状态
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)

  // 省市区三级数据状态
  const [province, setProvince] = useState<IresList>([])
  const [city, setCity] = useState<IresList>([])
  const [district, setDistrict] = useState<IresList>([])
  // 医院类型状态
  const [hosTypes, setHosTypes] = useState<IresList>([])
  useEffect(() => {
    getHospitalList(page, pageSize) // 获取表格数据
    getProvince() //获取省数据
    getHospitalType() //获取医院类型
  }, [])
  const columns: ColumnsType<IhospitalItem> = [
    {
      title: '序号',
      render: (a, b, index) => index + 1,
      align: 'center',
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      render(imgData) {
        return (
          <img width="80" src={'data:image/jpeg;base64,' + imgData} alt="" />
        )
      },
    },
    {
      title: '医院名称',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      dataIndex: 'param',
      render(_) {
        return _.hostypeString
      },
    },
    {
      title: '详细地址',
      dataIndex: 'param',
      render(_) {
        return _.fullAddress
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(status) {
        return status ? '已上点' : '未上线'
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },

    {
      title: '操作',
      dataIndex: 'status',
      render: (status, records) => (
        <Space size="middle">
          <Button
            type="primary"
            onClick={() => {
              navigate(`/syt/hospital/hospitalList/show`, {
                state: records.id,
              })
            }}
          >
            查看
          </Button>
          <Button type="primary">排班</Button>
          <Button type="primary">{status ? '下线' : '上线'}</Button>
        </Space>
      ),
      width: 200,
    },
  ]
  // 获取医院列表数据
  async function getHospitalList(page: number, pageSize: number) {
    setLoading(true)
    let result
    if (flag) {
      // 要有筛选条件
      // 获取表单中的其他参数
      const params = form.getFieldsValue()
      result = await reqGetHospitalList({ page, pageSize, ...params })
    } else {
      //不需要有筛选条件
      result = await reqGetHospitalList({ page, pageSize })
    }

    // console.log(result)
    setHospitalList(result.content)
    setTotal(result.totalElements)
    setLoading(false)
  }

  // 获取省数据
  async function getProvince() {
    const result = await reqGetProvince()
    setProvince(result)
  }

  // 获取医院类型
  async function getHospitalType() {
    const result = await reqGetCityOrDistrict('10000')
    setHosTypes(result)
  }

  // 表单查询按钮触发的事件
  function onFinish() {
    flag = true
    getHospitalList(1, pageSize)
    setPage(1)
  }
  return (
    <Card>
      <Form
        layout="inline"
        form={form}
        onValuesChange={(changedValues, allValues) => {
          // console.log(changedValues, allValues)
          flag = false
        }}
        onFinish={onFinish}
      >
        <Form.Item name="provinceCode">
          <Select
            placeholder="请选择省"
            style={{ width: 200 }}
            onChange={async (value, option) => {
              // value就是选择的省数据的编码
              // console.log(value, option)
              const result = await reqGetCityOrDistrict(value)
              setCity(result)
              // 清空市和区选中的数据
              form.setFieldsValue({
                cityCode: undefined,
                districtCode: undefined,
              })
            }}
          >
            {province.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="cityCode">
          <Select
            placeholder="请选择市"
            style={{ width: 200 }}
            onChange={async (value) => {
              const result = await reqGetCityOrDistrict(value)
              setDistrict(result)
              // 清空区选中的数据
              form.setFieldsValue({
                districtCode: undefined,
              })
            }}
          >
            {city.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="districtCode">
          <Select placeholder="请选择区" style={{ width: 200 }}>
            {district.map((item) => {
              return (
                <Option key={item.value} value={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>
        <Form.Item name="hoscode">
          <Input placeholder="医院编码"></Input>
        </Form.Item>
        <Form.Item name="hostype">
          <Select placeholder="医院类型" style={{ width: 200, marginTop: 10 }}>
            {hosTypes.map((item) => {
              return (
                <Option value={item.value} key={item.value}>
                  {item.name}
                </Option>
              )
            })}
          </Select>
        </Form.Item>
        <Form.Item name="status">
          <Select placeholder="医院状态" style={{ width: 200, marginTop: 10 }}>
            <Option value={1}>已上线</Option>
            <Option value={0}>未上线</Option>
          </Select>
        </Form.Item>
        <Form.Item style={{ marginTop: 10 }}>
          <Space>
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
              查询
            </Button>
            <Button
              onClick={() => {
                // 清空表单中所有的值
                form.resetFields()
                // 重新发送请求获取数据
                flag = false
                getHospitalList(1, pageSize)
                setPage(1)
              }}
            >
              清空
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Table
        loading={loading}
        bordered
        columns={columns}
        dataSource={hospitalList}
        style={{ marginTop: 20 }}
        rowKey="id"
        pagination={{
          current: page,
          pageSize,
          total,
          showTotal(total) {
            return `总共${total}条`
          },
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: [5, 10],
          onChange(page, pageSize) {
            setPage(page)
            setPageSize(pageSize)
            getHospitalList(page, pageSize)
          },
        }}
      ></Table>
    </Card>
  )
}
